package cn.nanmeishu;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib测试Model
 */
public class CGlibModel {
    public String test(){
        System.out.println("test helloWorld");
        return "hello World";
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CGlibModel.class);
        //不改变CGlibModel源码的基础上，改变里面的test方法的返回值
        enhancer.setCallback(new FixedValue() {
            @Override
            public Object loadObject() throws Exception {
                return "my cglib";
            }
        });
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("test方法执行前。。。。。");
                Object rs = methodProxy.invokeSuper(o,args); //执行test方法
                System.out.println("test方法执行后.....");
                return rs;
            }
        });
        //动态创建代理类
        CGlibModel cGlibModel=(CGlibModel) enhancer.create();
        System.out.println(cGlibModel.test());
    }
}
